package com.zzb;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class UrlRequestUtil {

	public static void main(String[] args) {
		String accessToken = "rmJQ1yYqa6rKzbIcZR13ot_Vu0FkLZRkL76EQHSMRytOdu-BEGe6GP37uCyRGxDt7x2_vpjg94O_dsV3LzZ_WtWjGKFIlH7YEy4SK7r-CviVXMcRARL08q8pjAnuQhnGPbD37P32ugINKDhGbJFHcQ";
		File file = new File(
				"C:\\Users\\Administrator\\Pictures\\f2c213ec54e736d1382f0e4999504fc2d46269fb.jpg");

		new UrlRequestUtil().uploadmedia("image", accessToken, file, "");
	}

	String result = "";
	String end = "\r\n";
	String twoHyphens = "--"; // 用于拼接
//	String boundary = "*****"; // 用于拼接 可自定义
	URL submit = null;

	/**
	 * 上传多媒体文件到微信公众平台
	 * 
	 * @param fileType
	 *            文件类型
	 * @param access_token
	 *            //在微信平台获取到的凭证
	 * @param file
	 *            文件流
	 * @param content_type
	 *            文件类型
	 * @return
	 */
	public void uploadmedia(String fileType, String access_token, File file,
			String content_type) {
		String requestUrl = "http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token=" + access_token + "&type="
				+ fileType;
		try {
			submit = new URL(requestUrl);
			HttpURLConnection conn = (HttpURLConnection) submit
					.openConnection();
			conn.setDoInput(true);
			conn.setDoOutput(true);

			conn.setRequestMethod("POST");
			conn.setRequestProperty("Connection", "Keep-Alive");
			conn.setRequestProperty("Content-Type", "multipart/form-data;" );
			// 获取输出流对象，准备上传文件
			OutputStream dos = conn.getOutputStream();
			dos.write((twoHyphens + end).getBytes());
			dos.write(("Content-Disposition: form-data; name=\""
					+ file.getName() + "\";filename=\"" + file.getName()
					+ ";filelength=\"" + file.length() +"content-type=\"image/jpeg\""+ end).getBytes());
			dos.write(end.getBytes());
			// 对文件进行传输
			FileInputStream fis = new FileInputStream(file);
			byte[] buffer = new byte[8192]; // 8k
			int count = 0;
			while ((count = fis.read(buffer)) != -1) {
				dos.write(buffer, 0, count);
			}
			fis.close(); // 关闭文件流

			dos.write(end.getBytes());
			dos.write((twoHyphens  + end).getBytes());
			dos.flush();

			InputStream is = conn.getInputStream();
			InputStreamReader isr = new InputStreamReader(is, "utf-8");
			BufferedReader br = new BufferedReader(isr);
			result = br.readLine();
			dos.close();
			is.close();
			System.out.println(result);
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("与服务器连接发生异常错误:" + e.toString());
			System.out.println("连接地址是:" + requestUrl);

		}
	}
}